from web.forms.account import RegisterModelForm, SendSmsForm, LoginSmsForm, LoginForm,ResetModelForm,UserForm,UserresetForm
from utils.image_code import check_code
from django.utils import timezone
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from utils.pagination import Pagination
from web import models
from utils.block import BlockChainOperation
from web.forms.order import OrderModelForm
from io import BytesIO
from django.db.models import Q
from django.db.models import Count
import json

def register(request):
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'register.html', {'form': form})
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        # models.UserInfo.objects.create(username=form.cleaned_data['username'],email=form.cleaned_data['email'],mobile_phone=form.cleaned_data['mobile_form'],password=form.cleaned_data['password'])
        return JsonResponse({"status": True, 'data': '/login'})

    return JsonResponse({'status': False, 'error': form.errors})


"""发送短信"""


def send_sms(request):
    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():
        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})


"""短信登录"""


def login_sms(request):
    if request.method == 'GET':
        form = LoginSmsForm
        return render(request, 'login_sms.html', {"form": form})

    form = LoginSmsForm(request.POST)
    if form.is_valid():
        # 校验正确则登陆成功,获取用户
        mobile_phone = form.cleaned_data['mobile_phone']
        user_object = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()

        # 将用户信息写入session
        request.session['user_id'] = user_object.id
        request.session.set_expiry(60 * 60 * 24 * 14)
        return JsonResponse({'status': True, 'data': "/order/manage/"})

    return JsonResponse({'status': False, 'error': form.errors})


"""用户名和密码登录"""


def login(request):
    if request.method == "GET":
        form = LoginForm(request)
        return render(request, 'login.html', {'form': form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']

        user_object = models.UserInfo.objects.filter(Q(mobile_phone=username) | Q(email=username)).first()
        if not user_object:
            have_time = 4 - user_object.failcount
            form.add_error(f'username', f'手机号邮箱错误或密码错误！您还有{have_time}次机会')
            # 用户账号错误，更新failcount值
            models.UserInfo.objects.filter(id=user_object.id).update(failcount=user_object.failcount + 1)
            models.UserInfo.objects.filter(id=user_object.id).update(lasttime=timezone.now())
            return render(request, 'login.html', {'form': form})
        now_time = timezone.now()
        last_time = user_object.lasttime
        timediff = (now_time-last_time).seconds
        # 判断密码是否正确之前，先判断登录次数是否受限
        if user_object.failcount >= 5 and timediff <= 60:
            form.add_error('username', '您已连续登录失败超过5次，请60秒后重试')
            return render(request, 'login.html', {'form': form})
        if user_object.password == password:
            # 用户密码正确，更新failcount值
            if user_object.failcount > 0:
                models.UserInfo.objects.filter(Q(mobile_phone=username) | Q(email=username)).update(failcount=0)
            # 将用户信息写入session
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60 * 60 * 24 * 14)
            return redirect('order_manage')
        have_time = 4-user_object.failcount
        form.add_error(f'username', f'手机号邮箱错误或密码错误！您还有{have_time}次机会')
        # 用户密码错误，更新failcount值
        models.UserInfo.objects.filter(id=user_object.id).update(failcount=user_object.failcount+1 )
        models.UserInfo.objects.filter(id=user_object.id).update(lasttime=timezone.now())
    return render(request, 'login.html', {'form': form})


"""请求获取验证码图片"""


def image_code(request):
    image_object, code = check_code()
    stream = BytesIO()
    image_object.save(stream, 'png')
    request.session['image_code'] = code
    request.session.set_expiry(60)
    return HttpResponse(stream.getvalue())


"""注销"""


def logout(request):
    request.session.flush()
    return redirect('login')


"""充值密码"""



def reset(request):
    if request.method == 'GET':
        form = ResetModelForm
        return render(request, 'reset.html', {"form": form})

    form = ResetModelForm(request.POST)
    if form.is_valid():
        # 校验正确则登陆成功,获取用户
        print(form.cleaned_data)
        mobile_phone = form.cleaned_data['mobile_phone']
        user_object = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()

        if user_object:
            models.UserInfo.objects.filter(mobile_phone=mobile_phone).update(password=form.cleaned_data['password'])
        return JsonResponse({'status': True, 'data': "/login/"})

    return JsonResponse({'status': False, 'error': form.errors})



def index(request):
    return render(request,'index.html')

    """订单列表"""
def order_manage(request):
    form = OrderModelForm
    data_dict = {}
    # 判断是否有搜索条件
    search_data = request.GET.get('search', "")
    if search_data:
        data_dict["order_id__contains"] = search_data

    queryset = models.Order.objects.filter(**data_dict).order_by("id")

    page_object = Pagination(request, queryset)

    context = {
        "search_data": search_data,
        "form":form,
        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html()  # 页码
    }
    return render(request, 'order_manage.html', context)

def order_add(request):
    form = OrderModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return JsonResponse({'status':True})
    return JsonResponse({'status':False,'error':form.errors})

def order_block(request):
    project_dict = models.Block.objects.all()
    return render(request,'order_block.html',{'project_dict':project_dict})

def block_add(request):
    nid = request.GET.get('nid')
    # data_dict = {}
    # # 判断是否有搜索条件
    # search_data = request.GET.get('search', "")
    # if search_data:
    #     data_dict["ordedr_id__contains"] = search_data
    #
    # queryset = models.Order.objects.filter(**data_dict).order_by("id")
    #
    # page_object = Pagination(request, queryset)
    #
    # context = {
    #     "search_data": search_data,
    #
    #     "queryset": page_object.page_queryset,  # 分完页的数据
    #     "page_string": page_object.html()  # 页码
    # }

    last_blockinfo = BlockChainOperation.get_last_block()
    # 判定是否存在创世区块，如无则创建
    if last_blockinfo is None:
        BlockChainOperation.create_generate_block()
    order = models.Order.objects.filter(id=nid).first()
    block = models.Block.objects.filter(Q(order_id=order.order_id) & Q(customer_id=order.customer_id) & Q(product_id=order.product_id)).first()
    if block:
        return redirect('default')
    BlockChainOperation.add_block(nid)
    return redirect('order_block')

def order_edit(request,nid):
    id = nid
    row_object = models.Order.objects.filter(id=id).first()
    if request.method=="GET":
        form = OrderModelForm(instance=row_object)
        return render(request,"order_edit.html",{"form":form})
    form = OrderModelForm(instance=row_object,data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('order_manage')
    return render(request,'order_edit.html',{'form':form})

def order_delete(request,nid):
    models.Order.objects.filter(id=nid).delete()
    return redirect('order_manage')

def order_blockinfo(request):
    id = request.GET.get('id')
    # order_id = request.GET.get('order_id')
    # customer_id = request.GET.get('customer_id')
    # product_id = request.GET.get('product_id')
    block_info = models.Block.objects.filter(id=id).first()
    block = block_info.block
    real_hash = BlockChainOperation.getRealHash(id)
    now_hash = BlockChainOperation.getNowHash(block)
    block=json.loads(block)
    order=json.loads(block["data"])
    import qrcode
    img = qrcode.make(real_hash)
    img.save("web/static/image/some_file.png")
    return render(request,'blockinfo.html',{"order":order,"real_hash":real_hash,"now_hash":now_hash})

def image_photo(request):
    imagepath = "web/static/image/some_file.png"
    image_data = open(imagepath, "rb").read()
    print(image_data)
    return HttpResponse(image_data, content_type="image/png")

def echarts(request):


    return render(request,'echarts.html')

def pie(request):
    data_list = models.Order.objects.all().values('region').annotate(Count('region'))

    data=[]
    for i in data_list:
        data.append({"name":i['region'],"value":i['region__count']})
    result = {
        "status": True,
        "data": data
    }
    print(result)
    return JsonResponse(result)

def pillar(request):
    data_list = models.Order.objects.all().values('region').annotate(Count('region'))

    xdata=[]
    sdata=[]
    for i in data_list:
        xdata.append(i['region'])
        sdata.append(i['region__count'])
    result = {
        "status": True,
        "xdata": xdata,
        "sdata": sdata,
    }
    print(result)
    return JsonResponse(result)


def default(request):
    return render(request,'default.html')
